package com.example.testapp.data

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import androidx.sqlite.db.SupportSQLiteDatabase
import com.example.testapp.data.dao.BalanceDao
import com.example.testapp.data.dao.BalanceImageDao
import com.example.testapp.data.dao.BalanceProcessRecordDao
import com.example.testapp.data.entity.Balance
import com.example.testapp.data.entity.BalanceImage
import com.example.testapp.data.entity.BalanceProcessRecord
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

/**
 * 应用数据库
 */
@Database(
    entities = [
        Balance::class,
        BalanceImage::class,
        BalanceProcessRecord::class
    ],
    version = 1,
    exportSchema = false
)
@TypeConverters(DateConverters::class)
abstract class AppDatabase : RoomDatabase() {

    /**
     * 获取账单DAO
     * @return 账单DAO
     */
    abstract fun balanceDao(): BalanceDao

    /**
     * 获取账单图片DAO
     * @return 账单图片DAO
     */
    abstract fun balanceImageDao(): BalanceImageDao

    /**
     * 获取账单处理记录DAO
     * @return 账单处理记录DAO
     */
    abstract fun balanceProcessRecordDao(): BalanceProcessRecordDao

    companion object {
        /**
         * 单例实例
         */
        @Volatile
        private var INSTANCE: AppDatabase? = null

        /**
         * 数据库名称
         */
        private const val DATABASE_NAME = "kitty_balance.db"

        /**
         * 数据库操作线程池
         */
        private const val NUMBER_OF_THREADS = 4
        @JvmField
        val databaseWriteExecutor: ExecutorService = Executors.newFixedThreadPool(NUMBER_OF_THREADS)

        /**
         * 获取数据库实例
         * @param context 上下文
         * @return 数据库实例
         */
        @JvmStatic
        fun getDatabase(context: Context): AppDatabase {
            return INSTANCE ?: synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    AppDatabase::class.java,
                    DATABASE_NAME
                ).addCallback(sRoomDatabaseCallback).build()
                INSTANCE = instance
                instance
            }
        }

        /**
         * 数据库创建回调
         */
        private val sRoomDatabaseCallback = object : RoomDatabase.Callback() {
            override fun onCreate(db: SupportSQLiteDatabase) {
                super.onCreate(db)

                // 数据库创建时可以执行一些初始化操作
                databaseWriteExecutor.execute {
                    // 可以添加一些初始数据
                }
            }
        }
    }
} 